<template>
  <div class="relative">


    <div class="index overauto flex justify-center"
         style="width: 100vw;height: 100vh;overflow-x: hidden;">
      <div class="content" v-infinite-scroll="loadMore">

        <div class="logo w-[100%] flex justify-between items-center">

          <div class="stepPos  w-[230PX]">

          </div>
          <div class="logoBg bg"
               :style="`background-image: url(${ website.webLogo });background-size:contain;`">

          </div>

          <div class="search flex items-center">
            <div>
              <el-input/>
            </div>

            <div class="w-[20PX] h-[20PX] bg ml-[15PX]"
                 style="background-image: url(https://img.alicdn.com/imgextra/i3/801089336/O1CN01PrlUhK2IpwkZoPbOm_!!801089336.png)">

            </div>


            <div class="w-[20PX] h-[20PX] bg ml-[15PX] more"
                 @click="handleBtnClick({type:'modal'})"
                 style="background-image: url(https://img.alicdn.com/imgextra/i1/801089336/O1CN01X8e0Nc2Ipwkb692Yu_!!801089336.png)">

            </div>


          </div>

        </div>

        <div class="line w-[100%] h-[1PX] bg-[#F7F7F7] mx-[15px]"></div>


        <div class="tab nvaTab mt-[60PX] flex-center cursor-pointer" style="gap:50px;">
          <div
            @click="handleBtnClick({type:'tab',index:-1})"
            class="transition"
            :class="`${ activeTab == -1 ? 'text-[#FD4442]' : '#333333' }`"
          >
            {{ language.home }}
          </div>


          <div
            v-for="(item,index) in nav" :key="index"

          >
            <el-popover
              v-if="item.children"

              placement="bottom"
              :width="`505PX`"
              trigger="hover"
            >
              <template #reference>
                <div
                  @click="handleBtnClick({type:'tab',index})"
                  class="transition"
                  :class="`${ index == activeTab ? 'text-[#FD4442]' : '#333333' }`"
                >
                  {{ item.name }}
                </div>
              </template>

              <template #default>
                <div class="px-[10PX] py-[10PX] flex flex-wrap">
                  <div class="w-[50%] cursor-pointer"
                       v-for="(it,idx) in item.children"
                       :key="idx"
                       @click="handleBtnClick({type:'categorySub',index,idx})"
                  >{{ it.name }}
                  </div>
                </div>
              </template>
            </el-popover>

            <div
              v-else
              @click="handleBtnClick({type:'tab',index})"
              class="transition"
              :class="`${ index == activeTab ? 'text-[#FD4442]' : '#333333' }`"
            >
              {{ item.name }}
            </div>

          </div>


        </div>

        <div class="swiper mt-[15PX]" v-if="activeTab==-1">
          <el-carousel :autoplay="true">
            <el-carousel-item v-for="item in website?.carousel?.split(',')" :key="item">

              <div class="swiper-item bg"
                   :style="`background-image: url(${ item });background-size:contain`">
              </div>

            </el-carousel-item>
          </el-carousel>
        </div>


        <div v-for="(item,index) in computeCategory" :key="index">

          <div v-if="item.type == 2">
            <div class="titleTxt text-[20PX] text-bold mt-[60PX]">
              {{ item.name }}
            </div>

            <div class="line bg-[#F7F7F7] w-[100%] h-[1PX] mt-[15PX]">

            </div>

            <div class="productList flex mt-[15PX] flex-wrap">
              <div class="productLi"

                   @click="handleBtnClick({type:'product',id:it.productId})"

                   v-for="(it,idx) in product[index]?.list || []" :key="idx">
                <div class="productBg  bg"
                     :style="`background-image: url(${ it.productCover });background-size:contain;`"
                >

                </div>

                <div class="title mt-[10PX] px-[10PX] ">
                  {{ it.productTitle }}
                </div>

                <div class="price mt-[10PX] px-[10PX] flex-center text-[#FD4442]">
                  {{ it.currencySymbol }}{{ it.discountedPrice || it.originalPrice }}
                </div>
              </div>
            </div>
          </div>

          <div v-if="item.type == 1">

            <div class="subProduct titleTxt mt-[60PX] flex items-center h-[30PX]"
                 style="gap: 15PX;">

              <div
                class=" transition text-[20PX] text-bold"
              >
                {{ item.name }}
              </div>


              <div v-for="(it,idx) in generateProductCategoryList(item.categoryIds)" :key="idx"
                   class=" transition cursor-pointer"
                   @click="handleBtnClick({type:'subTab',index,idx,item,it})"
                   :class="`${ idx == productCategoryTab[index] ? 'text-[18PX] text-bold' : '' }`"
              >
                {{ it.name }}
              </div>

              <div>

              </div>

              <div>

              </div>

            </div>

            <div class="mt-[10px] flex items-center h-[30PX]">
              <div
                class="flex items-center"
                style="gap:10px"

                v-if="productCategoryTab[index]>-1"
              >
                <div class="text-[14PX]  cursor-pointer transition"
                     v-for="(z,ix) in  generateProductCategoryList(item.categoryIds)[productCategoryTab[index]].children || []"
                     :key="ix"

                     @click="handleBtnClick({ type:'thirdTab',index,idx:productCategoryTab[index],ix,it:z })"
                     :class="`${ productThirdCategoryTab[`${ index }${ productCategoryTab[index] }`] == ix ? 'text-[#999999]' : 'text-[#E4E4E4]' }`"
                >
                  {{ z.name }}
                </div>
              </div>

            </div>

            <div class="line bg-[#F7F7F7] w-[100%] h-[1PX] mt-[15PX]">

            </div>

            <div class="subProductList flex mt-[15PX] flex-wrap">

              <div
                v-for="(it,idx) in (product[index]?.list || []).filter((i,ii)=>{ return ii<2 })"
                :key="idx"
                @click="handleBtnClick({type:'product',id:it.id})"


                class="big1 subProductLi w-[585PX] px-[30PX] py-[44PX] bg-[#FAFAFA] rounded-[8PX] flex  items-center"

              >
                <div class=" w-[242PX] h-[242PX] bg"
                     :style="`background-image: url(${it.cover});background-size:contain;`"
                >

                </div>

                <div class="ml-[25PX]">
                  <div class="title mt-[15PX] w-[268PX]" style="text-align: left;">
                    {{ it.titleExternal }}
                  </div>

                  <div class="title mt-[15PX] w-[268PX] text-[10PX] text-[#666666]"
                       style="text-align: left;">
                    {{ it.subtitle }}
                  </div>

                  <div class=" mt-[15PX]  w-[268PX] text-[#FD4442]">
                    {{ it.currencySymbol }}{{ it.discountedPrice || it.originalPrice }}
                  </div>

                  <div class="flex">
                    <div class="px-[20PX] py-[5PX] bg-[#000] text-[#fff] mt-[35PX] rounded-[5PX]">
                      {{ language.buyNow }}
                    </div>
                  </div>

                  <!--                  <el-button class="mt-[35PX]" color="#333333">立即购买</el-button>-->

                </div>


              </div>


              <div class="productLi  bg-[#FAFAFA] py-[15PX] rounded-[8PX]"
                   :class="idx<2 ? 'smallShow' : ''"
                   v-for="(it,idx) in (product[index]?.list || [])"
                   :key="idx"
                   @click="handleBtnClick({type:'product',id:it.id})"
              >
                <div class=" productShadow"
                >

                  <div class="w-[242PX] h-[242PX] bg productBg"
                       :style="`background-image: url(${ it.cover });margin:0 auto;background-size:contain;`">

                  </div>
                </div>

                <div class="title mt-[10PX] px-[10PX]">
                  {{ it.titleExternal }}
                </div>

                <div class="price mt-[10PX] px-[10PX]  flex-center text-[#FD4442]">
                  {{ it.currencySymbol }}{{ it.discountedPrice || it.originalPrice }}
                </div>
              </div>
            </div>

          </div>


          <div class="mt-[15PX] flex-center" v-if="computeMore(index)">
            <div class="px-[25PX] py-[10PX] rounded-[8px] cursor-pointer"
                 style="border: solid 1px #f7f7f7"
                 @click="handleBtnClick({type:'more',index,item})">
              {{ language.more }}
            </div>
          </div>

        </div>


        <div class="mt-[15PX] pb-[50PX]">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="Consistency" v-for="(item,index) in policyList" :key="index"
                              :name="index">
              <template #title>
                <img
                  src="https://img.alicdn.com/imgextra/i4/1034622205/O1CN01Sh4Hsv1S9wPDDRYuZ_!!1034622205.png"
                  alt=""/>
                <p class="text-[#333] text-[14PX] mt-2 mb-2 ml-4px">{{ item.title }} </p>
              </template>
              <div v-html="item.detail">

              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

      </div>
    </div>


    <!-- 手机端菜单   -->
    <el-drawer
      size="80%"
      v-model="isShowDrawer"
      title="I am the title"
      direction="ltr"
    >


      <template #header>
        <div></div>
      </template>

      <div class=" flex justify-between bg-[#F4F4F4] h-[100%]">
        <div class="w-[40%] py-[30PX]">

          <div class="tab">


            <div v-for="(item,index) in nav" class="tab-li " :key="index"
                 @click="handleBtnClick({type:'tab',index})"

            >
              <div class="w-[100%]  px-[15PX] h-[40PX] flex transition flex-wrap items-center"
                   :class="activeTab ==index ? 'bg-[#fff] text-[#000] font-bold' : ''"
              >
                {{ item.name }}
              </div>

              <div v-show="activeTab ==index">
                <div v-for="(it,idx) in item.children||[]" :key="idx"
                     class=" px-[25PX] W-[100%] h-[40PX] flex items-center "
                     :class="activeTab ==index ? 'bg-[#fff]' : ''"
                >
                  <div class="w-[2PX] h-[14PX] bg-[#FD4442] mr-[3PX]">

                  </div>
                  {{ it.name }}
                </div>

              </div>

            </div>
          </div>

        </div>
        <div class="w-[60%] py-[30PX] bg-[#fff] px-[15PX]">
          <div
            v-for="(item,index) in computeCategory"
            :key="index"
            class="mt-[15PX]"
          >


            <div class="text-[#C7C7C7]">
              {{ item.name }}
            </div>

            <div class="flex" style="gap:5PX;"
                 v-if="item.type == 2"
            >
              <div class="px-[10PX] py-[5PX] mt-[5PX] bg-[#F4F4F4] rounded-[20PX] text-[10PX]"
                   @click="handleBtnClick({ type:'' })">
                {{ item.name }}
              </div>
            </div>

            <div class="flex" style="gap:5PX;"
                 v-if="item.type == 1"
            >
              <div class="px-[10PX] py-[5PX] mt-[5PX] bg-[#F4F4F4] rounded-[20PX] text-[10PX]"
                   v-for="(it,idx) in generateProductCategoryList(item.categoryIds)" :key="idx"


                   @click="handleBtnClick({type:'subTab',index,idx,item,it})"

              >
                {{ it.name }}
              </div>
            </div>


          </div>
        </div>
      </div>

    </el-drawer>


  </div>


</template>
<script lang="ts" setup>

import {getLanguage} from "@/utils/langue";

import {useRoute} from "vue-router";
import {getWebSiteProduct, getWebSiteCategory, getWebSiteProductByCategory} from "@/api/h5/web";

import {useMessage} from "@/hooks/web/useMessage";
import router from "@/router";
import {useAppStore} from "@/store/modules/app";
import {deepCopy, throttle} from "@/utils";


const message = useMessage();
const props = defineProps({
  areaInfo:{
    type: Object,
    required: false,
    default: () => {
    }
  },
  website: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  nav: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  allCategoryList: {
    type: Array,
    required: false,
    default: () => []
  },
  policyList: {
    type: Array,
    required: false,
    default: () => []
  }
});

const language = ref(getLanguage(props.areaInfo.language))


const initQueryParams = {
  pageSize: 10,
  pageNo: 1
}

const activeNames = ref("")

const queryParams = ref({})

const activeTab = ref(-1)

const activeSub = ref(-1)

const productCategoryTab = ref({})
const productThirdCategoryTab = ref({})

const isShowDrawer = ref(false)

const computeCategory = computed(() => {
  let list = props.nav || [];
  let lis = []
  if (activeTab.value == -1) {
    generateCategoryList(list, lis);
  } else {
    if (activeSub.value == -1) {
      if (list[activeTab.value].children) {
        generateCategoryList(list[activeTab.value].children, lis);
      } else {
        lis = [list[activeTab.value]]
      }

    } else {
      lis = [list[activeTab.value].children[activeSub.value]]
    }
  }

  return lis;
})

const product = ref({})

let productList = {}

const generateCategoryList = (list, lis) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].children) {
      generateCategoryList(list[i].children, lis);
    } else {
      lis.push(list[i]);
    }
  }
}


//组装成商品一级分类二级分类
const generateProductCategoryList = (categoryList, index) => {
  let list = [];
  categoryList.forEach(item => {
    //找到当前的类别
    let it = props.allCategoryList.find(at => {
      return at.id == item
    })

    if (it) {

      //如果没有父级
      if (!it.parentId) {
        //一级分类
        // 查看有没有加入到数组
        let isIn = list.find(at => {
          return at.id == item
        })
        if (!isIn) {
          list.push({
            ...it,
          })
        }
      } else {
        //如果有父级id  说明是二级分类
        //找到父级

        let parent = list.find(at => {
          return at.id == it.parentId
        })

        let parentCategory = props.allCategoryList.find(at => {
          return at.id == it.parentId
        })

        //如果父级没有加入过
        if (!parent) {

          list.push({
            ...parentCategory,
            children: [it]
          })
        } else {
          parent.children.push(it)
        }
      }

    }
  })
  return list
}

let isClick = false;

const handleBtnClick = throttle((e) => {
  let type = e.type;

  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  } finally {

  }

}, 1000)


const fn = {
  //点击一级导航分类
  tab({index}) {
    if (index != activeTab.value) {
      queryParams.value = {}
      productList = {}
      activeTab.value = index;
      activeSub.value = -1;

    }
  },
  //点击二级导航分类
  subTab({index, idx, item, it}) {
    if (idx != productCategoryTab.value[index]) {
      queryParams.value = {}
      productList[index] = [];
      productCategoryTab.value[index] = idx;

      isShowDrawer.value = false;

      queryProduct({
        type: 1,
        categoryIds: it.children ? it.children.map(item => {
          return item.id
        }) : [it.id]
      }, index)
    }
  },
  //点击二级商品导航
  thirdTab({index, idx, ix, it}) {
    queryParams.value = {}
    productList[index] = [];
    productThirdCategoryTab.value = {
      ...productThirdCategoryTab.value,
      [`${index}${idx}`]: ix
    }


    queryProduct({
      type: 1,
      categoryIds: [it.id]
    }, index)

  },
  //点击一级商品导航
  categorySub({index, idx}) {
    if (idx != activeSub.value) {
      queryParams.value = {}
      productList[index] = [];
      activeTab.value = index
      activeSub.value = idx;

    }
  },
  product({id}) {
    router.push(`/product?id=${id}&tenantId=${useAppStore().getTenantId}`)
  },
  more({index, item}) {
    let params = queryParams.value[index] || {...initQueryParams};
    let productVal = product.value[index];
    params.pageNo += 1;
    queryParams.value[index] = params

    queryProduct(item, index)
  },
  modal() {
    isShowDrawer.value = true
  }
}

const loadMore = () => {

}


const queryProduct = async (item, index) => {
  let callback;
  if (item.type == 2) {


    callback = await getWebSiteProduct({
      webNavId: item.id,
      ...(queryParams.value[index] || initQueryParams)
    })


  } else if (item.type == 1) {

    callback = await getWebSiteProductByCategory({
      ids: item.categoryIds.join(','),
      ...(queryParams.value[index] || initQueryParams)
    })
  }

  let pval = productList[index] || {};

  let list = pval.list || [];


  console.log(list, "=======================l")

  list = list.concat(callback.list);
  productList[index] = {
    list,
    total: callback.total
  }

  product.value[index] = productList[index]
}

const computeMore = (index) => {
  let queryData = queryParams.value[index] || {...initQueryParams}
  let total = product.value[index]?.total || 0;

  let page = Math.ceil(total / queryData.pageSize)

  return queryData.pageNo < page

}


watch(() => computeCategory.value, () => {
  computeCategory.value.forEach((item, index) => {
    queryProduct(item, index);
  })

}, {
  deep: true,
  immediate: true
})

onMounted(() => {
  let id = useRoute().query.id;
  if (id) {
    //获取大

    let idx = props.nav.findIndex(at => {
      return at.id == id
    })

    activeTab.value = idx;
  }

})
</script>
<style>
</style>
<style scoped lang="less">
@import "@/common";

.index {
  .content {
    width: 1200PX;
    height: 100%;
    padding: 0;

    .logo {
      height: 142PX;

      .stepPos {
        display: block;
      }

      .logoBg {
        width: 188PX;
        height: 60PX;
      }

      .search {
        width: 230PX;
      }
    }

    .more {
      display: none;
    }

    .top-title {
      font-size: 14PX !important;

      .bar {
        width: 4PX;
      }
    }

    .subTitle {
      font-size: 10PX !important;
    }

    .swiper {
      width: 100%;
      height: 552PX;

      .swiper-item {
        width: 100%;
        height: 552PX;
      }

      .benefit {
        width: 100%;
        height: 64PX;

        .qianggou-num {
          padding: 5PX 12PX;
        }
      }

      .cycle {
        width: 27PX;
        height: 27PX;
        border-radius: 5PX;
        background: #FD4442;
      }
    }


    .productList {
      gap: 60PX;


      .productLi {
        width: 358PX;

        .title {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          text-align: center;
        }

        .productBg {
          width: 358PX;
          height: 358PX;
        }

      }
    }


    .subProductList {
      gap: 30PX;


      .productLi {
        &.smallShow {
          display: none;
        }

        .productShadow {
          width: 277PX;
          height: 242PX;
        }

        .title {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          text-align: center;
          width: 242PX;
        }

        .productBg {
          width: 242PX;
          height: 242PX;
        }


      }

      .title {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: center;
      }
    }
  }

  .ft12 {
    font-size: 12PX !important;
  }
}

@media screen and (max-width: 640PX) {
  .index {
    .content {
      width: 100%;
      padding: 0 18PX;

      .logo {
        height: 60PX;

        .stepPos {
          display: none;
        }

        .logoBg {
          width: 106PX;
          height: 34PX;
        }

        .search {
          width: auto;
        }
      }

      .more {
        display: block;
      }

      .nvaTab {
        display: none;
      }

      .swiper {
        width: calc(100vw - 36PX);
        height: calc((100vw - 36PX) * (442 / 351));

        .swiper-item {
          width: 100%;
          height: 100%;
        }
      }

      .titleTxt {
        text-align: center;
        display: flex;
        justify-content: center;
      }

      .productList {
        gap: 10PX;


        .productLi {
          width: 163PX;
          background: #fafafa;
          padding: 15PX 0;
          border-radius: 8PX;

          .title {
            width: 163PX;
          }

          .productBg {
            width: 163PX;
            height: 163PX;
          }

        }
      }


      .subProductList {
        gap: 10PX;

        .big1 {
          display: none;
        }

        .productLi {
          &.smallShow {
            display: block;
          }

          .productShadow {
            width: 163PX;
            height: 163PX;
          }


          .title {
            width: 163PX;
          }

          .productBg {
            width: 163PX;
            height: 163PX;
          }


        }


        .title {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          text-align: center;
        }
      }


    }

    .ft12 {
      .font(18);
    }

  }
}

:deep(.el-carousel) {
  width: 100%;
  height: 100%;

  .el-carousel__container {
    width: 100%;
    height: 100%;
  }
}

:deep(.el-input-number) {
  width: 135PX;
  height: 30PX;

  .el-input-number__decrease, .el-input-number__increase {
    width: 28PX;
    height: 28PX;
    border-radius: 0PX;
  }

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
  }

  .el-icon {
    font-size: 14PX;
  }

}

:deep(.el-input) {
  height: 30PX;

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
    border-radius: 5PX;
  }


}

:deep(.el-textarea ) {
  height: 60PX !important;

  .el-textarea__inner {
    height: 60PX !important;
    font-size: 10PX;
  }

}


:deep(.el-select) {
  height: 30PX !important;

  .el-select__selected-item, .el-input__inner, .el-select__wrapper {
    height: 30PX !important;


  }

  .el-select__placeholder {
    display: flex !important;
    align-content: center;
    align-items: center;
  }

}

:deep(.el-form-item) {
  margin-bottom: 0PX;
  margin-top: 15PX;
}

:deep(.el-drawer__close) {
  display: none;
}

:deep(.el-drawer__header) {
  height: 0;
  padding: 0;
  margin: 0;
}

:deep(.el-drawer__body) {
  padding: 0;
}


:deep(.el-collapse-item__header) {
  height: 48PX !important;
}
</style>
